﻿using JESAI.Application.Abstractions.Sys;
using JESAI.Core.Attributes;
using JESAI.Platform.Domain.Sys.Repositories;
using JESAI.Uow;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    internal class OnlineFormService : IOnlineFormService
    {

        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IFormDataSourceRepository _formDataSourceRepository;

        public OnlineFormService(IUnitOfWorkManager unitOfWorkManager, IFormDataSourceRepository formDataSourceRepository)
        {
            _unitOfWorkManager = unitOfWorkManager;
            _formDataSourceRepository = formDataSourceRepository;
        }

        public async Task<string> GetData(string formId, string businessKey)
        {
            var db = _unitOfWorkManager.Db;
            var formDataSourceList = _formDataSourceRepository._DbQueryable.Where(x => x.FormId == formId.ToString()).ToList();

            var tableGroup = formDataSourceList.GroupBy(x => x.TableId);
            IDictionary<string,object> data = new Dictionary<string, object>();
            foreach (var group in tableGroup)
            {
                var tableName = group.FirstOrDefault().TableName;
                var list = db.Queryable<dynamic>().AS(tableName).Where("BusinessKey=@BusinessKey", new { BusinessKey = businessKey }).ToList();
                if (list.Count > 0)
                {
                     ExpandoObject tableData = list.First();
                    //把tableData的属性值转换为字典
                    foreach (var item in tableData)
                    {
                        var form = formDataSourceList.Where(x => x.Columns == item.Key).FirstOrDefault();
                        if (form != null)
                        {
                            data.Add(form.FormField, item.Value);
                        }
                        else
                        {
                            data.Add(item.Key, item.Value);
                        }
                    }
                }
            }

            return JsonConvert.SerializeObject(data);
        }

        public async Task Save(JObject formData)
        {
            var db = _unitOfWorkManager.Db;


            var formId = formData["FormId"];

            var formDataSourceList = _formDataSourceRepository._DbQueryable.Where(x => x.FormId == formId.ToString()).ToList();

            //var tableGroup = formDataSourceList.GroupBy(x => x.TableId);

            IDictionary<string, Dictionary<string, object>> data = new Dictionary<string, Dictionary<string, object>>();

            //循环遍历动态对象的属性，得到key和value
            foreach (var item in formData)
            {
                if (item.Key != "FormId")
                {
                    var form = formDataSourceList.Where(x => x.FormField == item.Key).FirstOrDefault();
                    if (form != null)
                    {
                        if (!data.ContainsKey(form.TableName))
                        {
                            data.Add(form.TableName, new Dictionary<string, object>());
                        }
                        var table = data[form.TableName];
                        table.Add(form.Columns, item.Value);
                    }
                }
            }
            var id = formData["Id"];
            foreach (var d in data)
            {
                var tableData = d.Value;
                var tableName = d.Key;
                if (id != null)
                {
                    //更新
                    tableData.Add("Id", id.ToString());
                    db.Updateable(tableData).AS(tableName).WhereColumns("Id").ExecuteCommand();
                }
                else
                {
                    //新增
                    tableData.Add("Id", Guid.NewGuid().ToString());
                    db.Insertable(tableData).AS(tableName).ExecuteCommand();
                }
            }
        }
    }
}
